/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package docview;

import docview.IObserver.Sender;
import docview.ColorTable;
import java.util.HashMap;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author Dema
 */
// интерфейс для строк из бд
class BDInterface
{
    public BDInterface()
    {

    }

    public RowBD getRowBD()
    {
        return null;
    }
};

public class TableAction implements ActionListener, ListSelectionListener{
    protected DocTable price;
    protected DocTable result;
    protected HashMap rowMap = new HashMap();
    protected HashMap rowBDMap = new HashMap();

    TableAction()
    {

    }

    public void setTrackTable(DocTable _table,Sender value)
    {
        if(value == Sender.PRICE)
            price = _table;
        else
            result = _table;
    }

    public void performAction()
    {
        int row = price.getColorTable().getSelectedRow();
        int [] rows = result.getColorTable().getSelectedRows();


    }

    public void insertBD()
    {
        // тут вставляю значения в бд
    }

    public RowBD createRowBD(String str, String value)
    {
        int firstOccurance = str.indexOf(value);
        char charAfter = str.charAt(firstOccurance+value.length());
        String first = str.substring(0, firstOccurance);
        String second = str.substring((firstOccurance+value.length()), str.length());
        String res = "";
        res+=first;
        res+=second;
        int[] id = new int[0];
        return new RowBD(res,id,firstOccurance,charAfter,0,0);
    }

    public void actionPerformed(ActionEvent ae) {
        Row row = new Row();
        row.setRowPrice(price.getColorTable().getPriceRows()[0]);
        row.setValueCol(price.getColorTable().getPriceCol());
        row.setRowsResult(result.getColorTable().getPriceRows());
        row.setValueColResult(result.getColorTable().getPriceCol());
        rowMap.put(row.getRowPrice(), row);
        price.getColorTable().clearPriceValue();
        result.getColorTable().clearPriceValue();
        Object c = price.getColorTable().getValueAt(row.getRowPrice(),row.getValueCol());
        for (int i = 0; i <row.getRowsResult().length; ++i)
        {
            result.getColorTable().setValueAt(c,row.getRowsResult()[i],row.getValueColResult());
        }

        String str = proccessRowForIden(row.getRowPrice());
        String value = c.toString();
        RowBD rowBD = createRowBD(str,value);
        rowBD.setValueColPrice(row.getValueCol());
        rowBD.setValueColResult(row.getValueColResult());
        rowBDMap.put(rowBD.getIden(), rowBD);

        // INSERT TO BD HERE
        insertBD();



    }

    public Iterator<BDInterface> fetchRowsBD()
    {
       // здесь мне нужен список всех строк от поставщика из бд
        List<BDInterface> list = new ArrayList();
        return list.iterator();
    }

    public Row formRowFromRowBD(RowBD rowBD)
    {
        Row row = new Row();
        row.setValueCol(rowBD.getValueColPrice());
        row.setValueColResult(rowBD.getValueColResult());
        
        //здесь я конверчу одно в другое

        return row;
    }

    public void fillResultTable(RowBD row)
    {
        // хаполнить результирующую таблицу строками по идентификаторам из бдж
    }
    
    public Row findInBD(int row)
    {
        String value = proccessRowForIden(row);
        Iterator it = fetchRowsBD();
        while(it.hasNext())
        {
            BDInterface bd = (BDInterface) it.next();
            RowBD rowBD = bd.getRowBD();
            int firstOccurance = rowBD.getValuePosition();
            char charAfter = rowBD.getCharAfterValue();
            int secondOccurance = value.indexOf(charAfter,firstOccurance);
            String first = value.substring(0, firstOccurance);
            String second = value.substring(secondOccurance, value.length());
            String res = "";
            res+=first;
            res+=second;
            if ( res.compareToIgnoreCase(rowBD.getIden()) == 0)
            {
                Row r = formRowFromRowBD(rowBD);
                fillResultTable(rowBD);
                return r;
            }
            
        
        
            
        }
        
        return null;
    }

    public void parseInputPrice()
    {
        int rowNumber = 0;
        for(int i = 0; i<price.getColorTable().getRowCount(); i++)
        {

            Row row = findInBD(i);
            if (row != null)
            {
                row.setRowPrice(i);
                int count = result.getColorTable().getRowCount();
                int[] rows = new int[count-rowNumber];
                for (int j = 0; j< rows.length; j++)
                {
                    rows[i] = rowNumber;
                    rowNumber++;
                }
                row.setRowsResult(rows);
                // should fill in row numbers from RESULT table!!!
                rowMap.put(i,row);
            }
            else
                price.getColorTable().highlightRow(i,i);

        }
    }

    public String proccessRowForIden(int row)
    {
        String str = new String("");
        int cols = price.getColorTable().getColumnCount();
        for (int i = 0; i< cols; i++)
        {
          str+= price.getColorTable().getValueAt(row,i);
        }
        str  = str.replace(" ", "");
        return str;
    }

    public void valueChanged(ListSelectionEvent lse) {
        try
        {
        price.getColorTable().clearRowSelection();
        result.getColorTable().clearRowSelection();
        int rowIndex = price.getColorTable().getSelectedRow();
        Row row = (Row) rowMap.get(rowIndex);
        if (row != null)
        {
            int[] rows = new int[1];
            rows[0] = row.getRowPrice();
            price.getColorTable().setRowSelection(rows,row.getValueCol());
            result.getColorTable().setRowSelection(row.getRowsResult(),row.getValueColResult());
            price.getColorTable().repaint();
            result.getColorTable().repaint();

        }
        }
        catch(Exception e)
        {
            
        }
    }

    public Row findRowByIndex(int index)
    {
        Collection c = rowMap.values();
        Iterator it = c.iterator();
        while(it.hasNext())
        {
            Row row = (Row) it.next();
            if (row.containsIndex(index))
                return row;
        }
        return null;
    }
}



class Row
{
    private int rowPrice;
    private int valueCol;
    private int[] rowsResult;
    private int valueColResult;

    public boolean containsIndex(int index)
    {
        for (int i  = 0; i < rowsResult.length; i++)
            if ( rowsResult[i] == index)
                return true;
        return false;
    }

    public int getRowPrice() {
        return rowPrice;
    }

    public void setRowPrice(int rowPrice) {
        this.rowPrice = rowPrice;
    }

    public int[] getRowsResult() {
        return rowsResult;
    }

    public void setRowsResult(int[] rowsResult) {
        this.rowsResult = rowsResult;
    }

    public int getValueCol() {
        return valueCol;
    }

    public void setValueCol(int valueCol) {
        this.valueCol = valueCol;
    }

    public int getValueColResult() {
        return valueColResult;
    }

    public void setValueColResult(int valueColResult) {
        this.valueColResult = valueColResult;
    }


    Row()
    {

    }

    Row (int _rowPrice, int _valueCol, int[] _rowsResult, int _valueColResult)
    {
        rowPrice = _rowPrice;
        valueCol = _valueCol;
        rowsResult = _rowsResult;
        valueColResult = _valueColResult;
    }

    public void changeResultRowIndex(int newOne, int oldOne)
    {
        for( int i = 0; i< rowsResult.length; i++)
            if (rowsResult[i] == oldOne)
            {
                rowsResult[i] = newOne;
                break;
            }


    }

}

class RowBD
{
    private String iden;
    private int[] id;
    private int valuePosition;
    private char charAfterValue;
    private int valueColPrice;
    private int valueColResult;

    public RowBD()
    {

    }

    public RowBD(String _iden, int[] _id,int _valuePos,char _c,int _valueColP, int _valueColR)
    {
        iden = _iden;
        id = _id;
        valuePosition = _valuePos;
        charAfterValue = _c;
        valueColPrice = _valueColP;
        valueColResult = _valueColR;

    }
    public char getCharAfterValue() {
        return charAfterValue;
    }

    public void setCharAfterValue(char charAfterValue) {
        this.charAfterValue = charAfterValue;
    }

    public int[] getId() {
        return id;
    }

    public void setId(int[] id) {
        this.id = id;
    }

    public String getIden() {
        return iden;
    }

    public void setIden(String iden) {
        this.iden = iden;
    }

    public int getValueColPrice() {
        return valueColPrice;
    }

    public void setValueColPrice(int valueColPrice) {
        this.valueColPrice = valueColPrice;
    }

    public int getValueColResult() {
        return valueColResult;
    }

    public void setValueColResult(int valueColResult) {
        this.valueColResult = valueColResult;
    }

    public int getValuePosition() {
        return valuePosition;
    }

    public void setValuePosition(int valuePosition) {
        this.valuePosition = valuePosition;
    }

}
